<template>
    <el-drawer v-model="drawerVisible" title="" direction="rtl" size="60%" :with-header="true">
        <div>
            <text style="color: #333333;font-size: 16px;font-weight: 600;">实名认证</text>&nbsp;
            <text style="color: #999999;font-size: 12px;">请填写认证信息并上传相关材料后提交申请，您将会在1~3个工作日内收到反馈，请留意</text>
        </div>
        <el-steps :space="200" :active="activeStep" finish-status="success" style="margin-top:10px">
            <el-step v-for="(step, index) in steps" :key="index" :title="step.title"></el-step>
        </el-steps>

        <div v-for="(step, index) in steps" :key="`content-${index}`" v-show="activeStep === index">
            <el-form :rules="rules" v-show="activeStep === 0" ref="formRef" style="max-width: 600px;margin-top:20px" :model="form"
                label-width="auto" label-position="top">
                <el-form-item label="营业执照" required="true">
                    <el-upload class="avatar-uploader" :show-file-list="false" :http-request="uploadAvatar"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="rowData.companyUrl" :src="rowData.companyUrl" class="avatar"
                            style="width: 300px;height: 170px;" />
                        <div v-else class="upload-square">
                            <div class="content">
                                <el-icon :size="20">
                                    <PictureFilled />
                                </el-icon>
                                <div class="">点击上传或拖拽文件到这里</div>
                                <div class="">支持的文件类型：.jpg或.png</div>
                            </div>
                        </div>
                        <div v-if="rowData.companyUrl" class="update-img">重新上传</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="企业名称" required="true">
                    <el-input v-model="rowData.companyName" />
                </el-form-item>
                <el-form-item label="统一社会信用代码" required="true">
                    <el-input v-model="rowData.companyCode" />
                </el-form-item>
                <el-form-item label="注册地址" required="true">
                    <el-input v-model="rowData.registeredAddress" />
                </el-form-item>
                <el-form-item label="营业期限" required="true">
                    <el-radio-group v-model="rowData.isTime">
                        <el-radio value="1" size="large">期限内有效</el-radio>
                        <el-radio value="0" size="large">永久/无有效期限</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <el-form :rules="rules2" v-show="activeStep === 1" ref="formRef2" style="max-width: 600px;margin-top:20px" :model="form"
                label-width="auto" label-position="top">
                <el-form-item label="法人身份证" required="true">
                    <div style="display: flex;">
                        <el-upload class="avatar-uploader" :show-file-list="false" :http-request="uploadAvatar2"
                            :before-upload="beforeAvatarUpload2">
                            <div>
                                <img v-if="rowData.cardFrontUrl" :src="rowData.cardFrontUrl" class="avatar"
                                    style="width: 300px;height: 170px;" />
                                <div v-else class="upload-square">
                                    <div class="content">
                                        <div>头像面</div>
                                        <el-icon :size="20">
                                            <PictureFilled />
                                        </el-icon>
                                        <div>点击上传或拖拽文件到这里</div>
                                        <div>支持的文件类型：.jpg或.png</div>
                                    </div>
                                </div>
                                <div v-if="rowData.cardFrontUrl" class="update-img">重新上传</div>
                            </div>
                        </el-upload>
                        <el-upload class="avatar-uploader" :show-file-list="false" :http-request="uploadAvatar3"
                            :before-upload="beforeAvatarUpload3">
                            <div style="margin-left:20px">
                                <img v-if="rowData.cardBackUrl" :src="rowData.cardBackUrl" class="avatar"
                                    style="width: 300px;height: 170px;" />
                                <div v-else class="upload-square">
                                    <div class="content">
                                        <div>国徽面</div>
                                        <el-icon :size="20">
                                            <PictureFilled />
                                        </el-icon>
                                        <div>点击上传或拖拽文件到这里</div>
                                        <div>支持的文件类型：.jpg或.png</div>
                                    </div>
                                </div>
                                <div v-if="rowData.cardBackUrl" class="update-img">重新上传</div>
                            </div>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="法人姓名" required="true">
                    <el-input v-model="rowData.cardName" />
                </el-form-item>
                <el-form-item label="证件号码" required="true">
                    <el-input v-model="rowData.cardCode" />
                </el-form-item>


                <!-- 手机号 -->
                <el-form-item label="手机号" required="true">
                    <div style="display: flex; width: 100%">
                        <el-input v-model="rowData.phone" />
                        <el-button style="margin-left: 8px" :disabled="smsCoolDown > 0" @click="handleSendSms">
                            {{ smsCoolDown > 0 ? `${smsCoolDown}s` : "获取验证码" }}
                        </el-button>
                    </div>
                </el-form-item>

                <!-- 验证码 -->
                <el-form-item label="短信验证码">
                    <div style="display: flex; width: 100%">
                        <el-input v-model="form.smsCode" placeholder="请输入验证码" />

                    </div>
                </el-form-item>
                <el-form-item label="账号昵称" required="true">
                    <el-input v-model="rowData.nickName" />
                </el-form-item>
            </el-form>
            <div v-show="activeStep === 2">
                <div
                    style="margin-top:20%;display: flex;justify-content: center;align-items: center;flex-direction: column;">
                    <img src="../assets/review.png" alt="">
                    <div style="font-size: 20px;font-weight: 600;color: #333;margin-top:10px">审核中</div>
                    <div style="font-size: 14px;font-weight: 500;color: #999;margin-top:10px">您将会在1~3个工作日内收到反馈，请留意</div>
                </div>
            </div>
            <div v-show="activeStep === 3">
                <div
                    style="margin-top:20%;display: flex;justify-content: center;align-items: center;flex-direction: column;">
                    <img src="../assets/identifysuccess.png" alt="">
                    <div style="font-size: 20px;font-weight: 600;color: #333;margin-top:10px">已认证</div>
                    <div style="font-size: 14px;font-weight: 500;color: #999;margin-top:10px">您的认证已成功，可以进行开播啦</div>
                </div>
            </div>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="prevStep" :disabled="activeStep === 0">上一步</el-button>
                <el-button @click="nextStep" :disabled="activeStep === steps.length - 1">下一步</el-button>

            </div>
        </template>
    </el-drawer>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, computed, reactive, defineProps, defineEmits, watch } from 'vue'
import { apiClient } from '@/utils/request'
import { getsendSms } from "@/api/login";
import { companyInforealName, review } from "@/api/personCenter";
import { ElMessage } from "element-plus";

const formRef = ref()
// 校验
const rules = {
    companyName: [
        { required: true, message: '请输入企业名称', trigger: 'blur' }
    ],
    companyCode: [
        { required: true, message: '请输入统一社会信用代码', trigger: 'change' }
    ],
    registeredAddress: [
        { required: true, message: '请输入注册地址', trigger: 'blur' }
    ],
}
const rules2 = {
    cardName: [
        { required: true, message: '请输入法人姓名', trigger: 'blur' }
    ],
    cardCode: [
        { required: true, message: '请输入证件号码', trigger: 'change' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'change' }
    ],
    nickName: [
        { required: true, message: '请输入账号昵称', trigger: 'blur' }
    ],
}
// 定义props接收父组件传递的数据
const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    rowData: {
        type: Object,
        default: () => ({})
    }
})
const form = reactive({
    smsCode: "",
});
const smsVerified = ref(false); // 是否已通过短信验证
const smsCoolDown = ref(0);
let smsTimer: any = null;

const activeStep = ref(0);


// const userImg = ref();
// const AvatarfaceImg = ref();
// const NationalEmblemImg = ref();

const steps = ref([
    {
        title: '上传营业执照',
    },
    {
        title: '法人基本信息',
    },
    {
        title: '提交审核',
    },
    {
        title: '完成',
    }
]);
// 个人信息
const beforeAvatarUpload = (rawFile: File) => {
    const isImage = rawFile.type.startsWith('image/');
    const isLt2M = rawFile.size / 1024 / 1024 < 2;
    if (!isImage) {
        ElMessage.error('请上传图片格式文件');
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB');
    }
    return isImage && isLt2M;
};
// 上传接口
const uploadAvatar = async ({ file }: { file: File }) => {
    try {
        const fd = new FormData();
        fd.append('file', file);
        const res = await apiClient.post('/user/upload', fd, {
            headers: { 'Content-Type': 'multipart/form-data' }
        });
        if (res.code === 200) {
            props.rowData.companyUrl = res.data;
            ElMessage.success('头像上传成功');
        } else {
            ElMessage.error('上传失败');
        }
    } catch (e) {
        console.error(e);
        ElMessage.error('网络异常，上传失败');
    }
};
// 法人正
const beforeAvatarUpload2 = (rawFile: File) => {
    const isImage = rawFile.type.startsWith('image/');
    const isLt2M = rawFile.size / 1024 / 1024 < 2;
    if (!isImage) {
        ElMessage.error('请上传图片格式文件');
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB');
    }
    return isImage && isLt2M;
};
// 上传接口
const uploadAvatar2 = async ({ file }: { file: File }) => {
    try {
        const fd = new FormData();
        fd.append('file', file);
        const res = await apiClient.post('/user/upload', fd, {
            headers: { 'Content-Type': 'multipart/form-data' }
        });
        if (res.code === 200) {
            props.rowData.cardFrontUrl = res.data;
            ElMessage.success('头像上传成功');
        } else {
            ElMessage.error('上传失败');
        }
    } catch (e) {
        console.error(e);
        ElMessage.error('网络异常，上传失败');
    }
};
// 法人反
const beforeAvatarUpload3 = (rawFile: File) => {
    const isImage = rawFile.type.startsWith('image/');
    const isLt2M = rawFile.size / 1024 / 1024 < 2;
    if (!isImage) {
        ElMessage.error('请上传图片格式文件');
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB');
    }
    return isImage && isLt2M;
};
// 上传接口
const uploadAvatar3 = async ({ file }: { file: File }) => {
    try {
        const fd = new FormData();
        fd.append('file', file);
        const res = await apiClient.post('/user/upload', fd, {
            headers: { 'Content-Type': 'multipart/form-data' }
        });
        if (res.code === 200) {
            props.rowData.cardBackUrl = res.data;
            ElMessage.success('头像上传成功');
        } else {
            ElMessage.error('上传失败');
        }
    } catch (e) {
        console.error(e);
        ElMessage.error('网络异常，上传失败');
    }
};

// 下一步
const nextStep = () => {
    // formRef.value.validate()
    // 企业
    if (activeStep.value === 0) {
        
        if (activeStep.value < steps.value.length - 1) {
            activeStep.value++;
        }
    } else if (activeStep.value === 1) {
        if(!form.smsCode) {
            ElMessage.warning('请输入验证码')
        } else {
            const parmas = {
            userId: Number(localStorage.getItem('userId')),

            companyUrl: props.rowData.companyUrl,
            companyName: props.rowData.companyName,
            companyCode: props.rowData.companyCode,
            registeredAddress: props.rowData.registeredAddress,
            isTime: props.rowData.isTime,

            smsCode: form.smsCode, 
            cardFrontUrl: props.rowData.cardFrontUrl,
            cardBackUrl: props.rowData.cardBackUrl,
            cardName: props.rowData.cardName,
            cardCode: props.rowData.cardCode,
            phone: props.rowData.phone,
            nickName: props.rowData.nickName,
        }
        companyInforealName(parmas)
            .then((res) => {
                if (res.code === 200) {
                    ElMessage.success('成功')
                        if (activeStep.value < steps.value.length - 1) {
                            activeStep.value++;
                        }
                    
                }
            })
            .catch((err) => {
                console.error('发送失败:', err);
            });

        }
        
    } else if (activeStep.value === 2) {
        // 审核中接口
        const parmas = {
            // id: props.rowData.id,
            reviewStatus: 0
        }
        review(parmas)
            .then((res) => {
                if (res.code === 200) {
                    ElMessage.success('成功')
                    if (activeStep.value < steps.value.length - 1) {
                        activeStep.value++;
                    }
                }
            })
            .catch((err) => {
                console.error('发送失败:', err);
            });
    }
};

const prevStep = () => {
    if (activeStep.value > 0) {
        activeStep.value--;
    }
};





// 定义emit用于通知父组件drawer状态变化
const emit = defineEmits(['update:visible'])

// 抽屉可见性状态
const drawerVisible = ref(props.visible)

// 监听父组件传入的visible变化
watch(() => props.visible, (newVal) => {
    drawerVisible.value = newVal
})

// 监听drawerVisible变化并通知父组件
watch(drawerVisible, (newVal) => {
    emit('update:visible', newVal)
})
/*  获取验证码  */
const handleSendSms = async () => {
    if (!props.rowData.phone) {
        ElMessage.warning("请先填写手机号");
        return;
    }
    try {
        await getsendSms(props.rowData.phone);
        ElMessage.success("验证码已发送");
        smsCoolDown.value = 60;
        smsVerified.value = false;
        smsTimer = setInterval(() => {
            smsCoolDown.value--;
            if (smsCoolDown.value <= 0) clearInterval(smsTimer);
        }, 1000);
    } catch {
        ElMessage.error("发送失败，请重试");
    }
};
</script>

<style scoped lang="scss">
.header {

    height: 100px;
    background: #F7F7F7;
    border-radius: 10px;
    padding: 10px;

    .content-flag {
        display: flex;

    }

    .square {
        display: flex;
        flex-direction: column;

        padding-right: 60px;


        .label {
            font-size: 14px;
            color: #999999;
        }

        .num {
            font-family: PingFang SC, PingFang SC;
            font-weight: 800;
            font-size: 20px;
            color: #2D7AF7;
        }
    }

    .square:not(:last-child) {
        border-right: 1px solid #EEEEEE;


    }

    .square:not(:first-child) {

        padding-left: 40px;

    }




}

.tab-area {
    margin-bottom: 20px;
}

.pagination-container {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 20px;
}

.custom-pagination {
    --el-pagination-hover-bg-color: #f5f7fa;
    --el-pagination-bg-color: transparent;
    --el-pagination-text-color: #606266;
    --el-pagination-button-disabled-bg-color: #f5f7fa;
    --el-pagination-button-disabled-text-color: #c0c4cc;
}

.pagination-pages {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
}

.pagination-btn {
    min-width: 32px;
    height: 32px;
    padding: 0;
    margin: 0 4px;
    background-color: transparent;
    border: 1px solid #dcdfe6;
    color: #606266;
    font-size: 14px;
    cursor: pointer;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.pagination-btn:hover {
    color: #409eff;
}

.pagination-btn.active {
    background-color: #409eff;
    color: #fff;
    border-color: #409eff;
}

.pagination-btn.disabled {
    color: #c0c4cc;
    cursor: not-allowed;
}

.upload-square {
    width: 300px;
    height: 169px;
    background: #F7F7F7;
    border-radius: 5px 5px 5px 5px;
    border: 1px solid #D1DEF5;

    .content {
        font-size: 14px;
        color: #999999;
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-top: 30px;

    }

}

.update-img {
    width: 300px;
    height: 29px;
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    position: absolute;
    bottom: 0;
    text-align: center;
}
</style>